package com.fulu.netty.luban.nio;

import java.nio.ByteBuffer;
import java.util.Arrays;

/**
 * buffer 的 slice方法根据position和limit截取一段数据进行操作
 * 截取出的buffer的array与原buffer地址指向同一个array
 */
public class Demo6 {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(10);
        for (int i = 0; i < buffer.capacity(); i++) {
            buffer.put((byte)i);
        }
        buffer.mark(); // 将当前position的值赋值给mark，与reset相反
        buffer.position(2);
        buffer.limit(8);
        ByteBuffer sliceBuffer = buffer.slice();
//        System.out.println(sliceBuffer.position());
//        System.out.println(sliceBuffer.limit());
//        System.out.println(sliceBuffer.capacity());
        for (int i = 0; i < sliceBuffer.capacity(); i++) {
            byte b = buffer.get();
            System.out.println(sliceBuffer.position());
            sliceBuffer.put((byte) (b * 2));
        }
        System.out.println(Arrays.toString(sliceBuffer.array()));
        System.out.println(sliceBuffer.capacity());
        System.out.println(Arrays.toString(buffer.array()));
        System.out.println(sliceBuffer);
        System.out.println(buffer);
        System.out.println(sliceBuffer.array());
        System.out.println(buffer.array());
        buffer.reset(); // 将mark赋值给position，与mark方法相反
    }
}
